#include "udp.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <time.h>

/////////////////////////////////////////////////////////////////////
int udp_init(MH_UDP *pudp)
{
    int ret = 0;

    if ((pudp->soc_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        printf("failed to open socket\n");
        return -1;
    }

    pudp->rem_addr.sin_family = AF_INET;
    pudp->rem_addr.sin_addr.s_addr = inet_addr("192.168.1.101");
    pudp->rem_addr.sin_port = htons(1000);

    pudp->loc_addr.sin_family = AF_INET;
    pudp->loc_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    pudp->loc_addr.sin_port = htons(1020);

    if(bind(pudp->soc_fd, (struct sockaddr *)&pudp->loc_addr, sizeof(pudp->loc_addr)) == -1)
    {
        perror("client Bind()error.");
        printf("errno = %d\n", errno);
        return -1;
    }

    return ret;
}
////////////////////////////////////////////////////////////////////
int udp_send_data(MH_UDP *pudp, char *buf, unsigned int size)
{
    int ret = -1;
    struct timeval timeout = {0, 200000};

    setsockopt(pudp->soc_fd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));
    ret = sendto(pudp->soc_fd, buf, size, 0, (struct sockaddr *)&pudp->rem_addr, sizeof(struct sockaddr_in));

    return ret;
}
///////////////////////////////////////////////////////////////////
int udp_recv_data(MH_UDP *pudp, char *buf, unsigned int size)
{
    int ret = 0;
    struct timeval timeout = { 0, 200000 };
    uint addr_len = sizeof(struct sockaddr_in);

    setsockopt(pudp->soc_fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
    ret = recvfrom(pudp->soc_fd, buf, size, 0, (struct sockaddr *)&pudp->loc_addr, &addr_len);
    return ret;
}

/////////////////////////////////////////////////////////////////////
int udp_close(MH_UDP *pudp)
{
    int ret;

    ret = close(pudp->soc_fd);
    pudp->soc_fd = -1;

    return ret;
}



